package com.txtsqlclient.domain;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class DataSourceFactory {

	private static DataSourceFactory factory;

	public final static List<DataSourceType> LEGAL_DATABASE_TYPES;

	public final static List<DataSourceType> LEGAL_FILE_DATASOURCE_TYPES;

	protected static Map<String, DataSourceType> types;

	static {
		LEGAL_DATABASE_TYPES = getLegalDatabaseTypes();
		LEGAL_FILE_DATASOURCE_TYPES = getLegalFileTypes();
	}

	/**
	 * Protected constructor to force singleton.
	 */
	protected DataSourceFactory() {
	}

	public static DataSourceFactory getInstance() {
		if (factory == null) {
			factory = new DataSourceFactory();
		}
		return factory;
	}

	protected static List<DataSourceType> getLegalDatabaseTypes() {
		List<DataSourceType> types = new LinkedList<DataSourceType>();
		List<DataSourceType> allTypes = DataSourceType.getAllTypes();
		for (DataSourceType type : allTypes) {
			if (type.isDatabase()) {
				types.add(type);
			}
		}
		return types;
	}

	protected static List<DataSourceType> getLegalFileTypes() {
		List<DataSourceType> types = new LinkedList<DataSourceType>();
		List<DataSourceType> allTypes = DataSourceType.getAllTypes();
		for (DataSourceType type : allTypes) {
			if (!type.isDatabase()) {
				types.add(type);
			}
		}
		return types;
	}

	public DataSource getDataSource(final DataSourceType dsType) {
		DataSource ds = null;
		if (LEGAL_DATABASE_TYPES.contains(dsType)) {
			ds = new Database(dsType);
		} else if (LEGAL_FILE_DATASOURCE_TYPES.contains(dsType)) {
			ds = new FileDataSource(dsType);
		} else {
			throw new IllegalArgumentException("Given Data Source Type, :"
					+ dsType
					+ " is neither a valid Database nor a File Data Source.");
		}
		return ds;
	}
}